<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"tallgy.gitee.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>
<meta name="description" content="WebWorker参考文章 12http:&#x2F;&#x2F;www.ruanyifeng.com&#x2F;blog&#x2F;2018&#x2F;07&#x2F;web-worker.htmlhttps:&#x2F;&#x2F;developer.mozilla.org&#x2F;zh-CN&#x2F;docs&#x2F;Web&#x2F;API&#x2F;Web_Workers_API    是什么​        简单来说就是为JavaScript提供了多线程。一些计算密集型或高延迟的任务，被 Worker 线程">
<meta property="og:type" content="article">
<meta property="og:title" content="WebWorker">
<meta property="og:url" content="http://tallgy.gitee.io/2021/11/06/JavaScript/%E9%9A%8F%E7%AC%94/WebWorker/index.html">
<meta property="og:site_name" content="tallgy&#39;s blog">
<meta property="og:description" content="WebWorker参考文章 12http:&#x2F;&#x2F;www.ruanyifeng.com&#x2F;blog&#x2F;2018&#x2F;07&#x2F;web-worker.htmlhttps:&#x2F;&#x2F;developer.mozilla.org&#x2F;zh-CN&#x2F;docs&#x2F;Web&#x2F;API&#x2F;Web_Workers_API    是什么​        简单来说就是为JavaScript提供了多线程。一些计算密集型或高延迟的任务，被 Worker 线程">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-06T06:49:25.000Z">
<meta property="article:modified_time" content="2023-06-25T08:57:29.338Z">
<meta property="article:author" content="tallgy">
<meta property="article:tag" content="随笔">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="WebWorker">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://tallgy.gitee.io/2021/11/06/JavaScript/%E9%9A%8F%E7%AC%94/WebWorker/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://tallgy.gitee.io/2021/11/06/JavaScript/%E9%9A%8F%E7%AC%94/WebWorker/","path":"2021/11/06/JavaScript/随笔/WebWorker/","title":"WebWorker"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>WebWorker | tallgy's blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">tallgy's blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#WebWorker"><span class="nav-number">1.</span> <span class="nav-text">WebWorker</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%98%AF%E4%BB%80%E4%B9%88"><span class="nav-number">1.1.</span> <span class="nav-text">是什么</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%BB%E7%BA%BF%E7%A8%8B%EF%BC%9A"><span class="nav-number">1.1.1.</span> <span class="nav-text">主线程：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Worker%E7%BA%BF%E7%A8%8B"><span class="nav-number">1.1.2.</span> <span class="nav-text">Worker线程</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#API"><span class="nav-number">2.</span> <span class="nav-text">API</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BAAPI"><span class="nav-number">2.1.</span> <span class="nav-text">创建API</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BB%E7%BA%BF%E7%A8%8B%E4%BD%BF%E7%94%A8API"><span class="nav-number">2.2.</span> <span class="nav-text">主线程使用API</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Worker%E7%BA%BF%E7%A8%8B%E4%BD%BF%E7%94%A8API"><span class="nav-number">2.3.</span> <span class="nav-text">Worker线程使用API</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">tallgy</p>
  <div class="site-description" itemprop="description">只是一个知识的搬运工</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">107</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">74</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://tallgy.gitee.io/2021/11/06/JavaScript/%E9%9A%8F%E7%AC%94/WebWorker/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="tallgy">
      <meta itemprop="description" content="只是一个知识的搬运工">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="tallgy's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          WebWorker
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-11-06 14:49:25" itemprop="dateCreated datePublished" datetime="2021-11-06T14:49:25+08:00">2021-11-06</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2023-06-25 16:57:29" itemprop="dateModified" datetime="2023-06-25T16:57:29+08:00">2023-06-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E9%9A%8F%E7%AC%94/" itemprop="url" rel="index"><span itemprop="name">随笔</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="WebWorker"><a href="#WebWorker" class="headerlink" title="WebWorker"></a>WebWorker</h1><p>参考文章</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">http://www.ruanyifeng.com/blog/2018/07/web-worker.html</span><br><span class="line">https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API</span><br></pre></td></tr></table></figure>



<h2 id="是什么"><a href="#是什么" class="headerlink" title="是什么"></a>是什么</h2><p>​        简单来说就是为JavaScript提供了多线程。一些计算密集型或高延迟的任务，被 Worker 线程负担了，主线程（通常负责 UI 交互）就会很流畅，不会被阻塞或拖慢。</p>
<p><strong>注意点</strong>：</p>
<ul>
<li>同源的限制</li>
<li>无法使用DOM对象，document，window，parent对象，可以使用navigator 和 location 对象。</li>
<li>和主线程通过消息进行通信</li>
<li>不能使用 alert 和 confirm 方法，但是可以使用 XMLHttpRequest 对象发出 AJAX 请求。</li>
<li>无法读取本地文件。</li>
</ul>
<p><strong>用法</strong>：</p>
<p>使用 new 调用 worker 函数，创建一个线程</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">const worker = new Worker(&#x27;xx.js&#x27;);</span><br></pre></td></tr></table></figure>

<p>​        参数是一个脚本文件，这个文件必须来自网络</p>
<h3 id="主线程："><a href="#主线程：" class="headerlink" title="主线程："></a>主线程：</h3><p>主线程通过 worker.postMessage() 向Worker发送消息</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">worker.postMessage(&#x27;Hello World&#x27;);</span><br><span class="line">worker.postMessage(&#123;method: &#x27;echo&#x27;, args: [&#x27;Work&#x27;]&#125;);</span><br></pre></td></tr></table></figure>

<p>​        参数就是传给worker的数据</p>
<p>主线程通过 worker.onmessage 监听函数，接收子线程发回的消息</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">worker.onmessage = function (event) &#123;</span><br><span class="line">	event.data.log;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​        事件对象的data属性可以获取 worker发来的数据</p>
<p>主线程关闭worker线程</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">worker.terminate();</span><br></pre></td></tr></table></figure>



<h3 id="Worker线程"><a href="#Worker线程" class="headerlink" title="Worker线程"></a>Worker线程</h3><p>worker线程需要一个监听函数，监听 message 事件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">self.addEventListener(&#x27;message&#x27;, function(e) &#123;</span><br><span class="line">	self.postMessage(&#x27;said: &#x27;, e.data);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>​        <code>self</code>代表子线程自身，即子线程的全局对象</p>
<p>所以等同于 this. 和 直接创建</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">this.addEventListener();</span><br><span class="line">addEventListener();</span><br></pre></td></tr></table></figure>

<p>​        也可以使用 self.onmessage 指定</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">self.onmessage = function (e) &#123;</span><br><span class="line">	self.postMessage(&#x27;said: &#x27;, e.data);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​        监听函数的参数是一个事件对象，data属性是主线程发来的数据</p>
<p>self.postMessage() 方法用来向主线程发送消息</p>
<p>self.close() 用于在Worker内部关闭自身。</p>
<h1 id="API"><a href="#API" class="headerlink" title="API"></a>API</h1><h2 id="创建API"><a href="#创建API" class="headerlink" title="创建API"></a>创建API</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">const worker = new Worker(jsUrl, options);</span><br><span class="line"></span><br><span class="line">var myWorker = new Worker(&#x27;worker.js&#x27;, &#123; name : &#x27;myWorker&#x27; &#125;);</span><br></pre></td></tr></table></figure>

<p>​        jsUrl,脚本网址,遵守同源策略，必须且是js脚本</p>
<p>​        options是一个配置对象，其中一个作用就是指定worker名称用来区分线程。</p>
<h2 id="主线程使用API"><a href="#主线程使用API" class="headerlink" title="主线程使用API"></a>主线程使用API</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Worker.onerror</span><br><span class="line">	指定 error 事件的监听函数。</span><br><span class="line">Worker.onmessage</span><br><span class="line">	指定 message 事件的监听函数，发送过来的数据在Event.data属性中。</span><br><span class="line">Worker.onmessageerror</span><br><span class="line">	指定 messageerror 事件的监听函数。发送的数据无法序列化成字符串时，会触发这个事件。</span><br><span class="line">Worker.postMessage()</span><br><span class="line">	向 Worker 线程发送消息。</span><br><span class="line">Worker.terminate()</span><br><span class="line">	立即终止 Worker 线程。</span><br></pre></td></tr></table></figure>



<h2 id="Worker线程使用API"><a href="#Worker线程使用API" class="headerlink" title="Worker线程使用API"></a>Worker线程使用API</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">self.name</span><br><span class="line">	Worker 的名字。该属性只读，由构造函数指定。</span><br><span class="line">self.onmessage</span><br><span class="line">	指定message事件的监听函数。</span><br><span class="line">self.onmessageerror</span><br><span class="line">	指定 messageerror 事件的监听函数。发送的数据无法序列化成字符串时，会触发这个事件。</span><br><span class="line">self.close()</span><br><span class="line">	关闭 Worker 线程。</span><br><span class="line">self.postMessage()</span><br><span class="line">	向产生这个 Worker 线程发送消息。</span><br><span class="line">self.importScripts()</span><br><span class="line">	加载 JS 脚本。</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E9%9A%8F%E7%AC%94/" rel="tag"># 随笔</a>
              <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
              <a href="/tags/WebWorker/" rel="tag"># WebWorker</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/11/06/%E6%B5%8F%E8%A7%88%E5%99%A8/Cookie%E3%80%81SessionStorage%E3%80%81LocalStorage%E7%9A%84%E5%8C%BA%E5%88%AB/" rel="prev" title="Cookie、SessionStorage、LocalStorage的区别">
                  <i class="fa fa-chevron-left"></i> Cookie、SessionStorage、LocalStorage的区别
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/11/06/%E9%9A%8F%E7%AC%94/RESTful/" rel="next" title="RESTful">
                  RESTful <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">tallgy</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
